package com.huaqin.punan;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import android.widget.Toast;

public class LocationService extends Service {
    
    public static final String TAG = "LocationService";
    public static final String SMS_GETLOCATION_BROADCAST = "com.huaqin.gps.location";
    private LocationManager location_manager;
    private Context context;
    private Timer timer;
    private Timer CellLocationTimer;
    private String LACProvider;
    
    //基站信息结构体
    public class SCell{
        public int MCC;
        public int MNC;
        public int LAC;
        public int CID;
    }
    
    //经纬度信息结构体
    public class SItude{
        public String latitude;
        public String longitude;
    }
    
    @Override
    public void onCreate() {
        Log.e(TAG, "====>>>onCreate");
        context = this;
        
		LACProvider = Settings.Secure.getString(getContentResolver(),
				Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        
        
//        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
//        .detectDiskReads()
//        .detectDiskWrites()
//        .detectNetwork()   // or .detectAll() for all detectable problems
//        .penaltyLog()
//        .build());
//        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
//        .detectLeakedSqlLiteObjects()
//        .detectLeakedClosableObjects()
//        .penaltyLog()
//        .penaltyDeath()
//        .build());
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "===>>>onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }
    
    @Override
    public void onStart(Intent intent, int startId) {
        Log.e(TAG, "===>>>onStart");
        
        Toast.makeText(context, "Service Started!!!", Toast.LENGTH_LONG).show();
        
        location_manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        String bestProvider = location_manager.getBestProvider(getCriteria(), true);
        Log.i(TAG, "bestProvider = "+bestProvider);
        //使用GPS信号定位
        location_manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
        
        
        //使用基站定位
        if(LACProvider.contains("network")){
            CellLocationTimer = new Timer();
            CellLocationTimer.schedule(new TimerTask(){
                @Override
                public void run() {
                    try {
                        SCell cell = getCellInfo();
                        SItude itude = getItude(cell);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }}, 1000);
        }
        
        timer = new Timer();
        timer.schedule(new TimerTask(){
            @Override
            public void run() {
                Intent intent = new Intent();
                intent.setAction(SMS_GETLOCATION_BROADCAST);
                intent.putExtra("GetLocation", false);
                //intent.putExtra("Longitude", "111");
                //intent.putExtra("Latitude", "222");
                sendBroadcast(intent);
                
                LocationService.this.stopSelf();
            }}, 10000);
        
        super.onStart(intent, startId);
    }
    
    // 位置监听
    private LocationListener locationListener = new LocationListener() {

        /**
         * 位置信息变化时触发
         */
        public void onLocationChanged(Location location) {

            String newLoc = "经度：" + location.getLongitude() + "纬度：" + location.getLatitude();
            Toast.makeText(context, newLoc, Toast.LENGTH_SHORT).show();
            
            Intent intent = new Intent();
            intent.setAction(SMS_GETLOCATION_BROADCAST);
            intent.putExtra("GetLocation", true);
            intent.putExtra("Longitude", String.valueOf(location.getLongitude()));
            intent.putExtra("Latitude", String.valueOf(location.getLatitude()));
            sendBroadcast(intent);
            timer.cancel();
            LocationService.this.stopSelf();
        }

        /**
         * GPS状态变化时触发
         */
        public void onStatusChanged(String provider, int status, Bundle extras) {
            switch (status) {
            // GPS状态为可见时
            case LocationProvider.AVAILABLE:
                Log.i(TAG, "当前GPS状态为可见状态");
                break;
            // GPS状态为服务区外时
            case LocationProvider.OUT_OF_SERVICE:
                Log.i(TAG, "当前GPS状态为服务区外状态");
                break;
            // GPS状态为暂停服务时
            case LocationProvider.TEMPORARILY_UNAVAILABLE:
                Log.i(TAG, "当前GPS状态为暂停服务状态");
                break;
            }
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }
    };
    
    /**
     * 返回查询条件
     * 
     * @return
     */
    private Criteria getCriteria() {
        Criteria criteria = new Criteria();
        // 设置定位精确度 Criteria.ACCURACY_COARSE比较粗略，Criteria.ACCURACY_FINE则比较精细
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        // 设置是否要求速度
        criteria.setSpeedRequired(false);
        // 设置是否允许运营商收费
        criteria.setCostAllowed(false);
        // 设置是否需要方位信息
        criteria.setBearingRequired(false);
        // 设置是否需要海拔信息
        criteria.setAltitudeRequired(false);
        // 设置对电源的需求
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        return criteria;
    }
    
    /**
     * 获取基站信息
     * 
     * @throws Exception
     */
    private SCell getCellInfo() throws Exception {
        SCell cell = new SCell();

        /** 调用API获取基站信息 */
        TelephonyManager mTelNet = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        GsmCellLocation location = (GsmCellLocation) mTelNet.getCellLocation();
        if (location == null)
            throw new Exception("获取基站信息失败");

        String operator = mTelNet.getNetworkOperator();
        int mcc = Integer.parseInt(operator.substring(0, 3));
        int mnc = Integer.parseInt(operator.substring(3));
        int cid = location.getCid();
        int lac = location.getLac();

        /** 将获得的数据放到结构体中 */
        cell.MCC = mcc;
        cell.MNC = mnc;
        cell.LAC = lac;
        cell.CID = cid;

        return cell;
    }
    
    /**
     * 获取经纬度
     * 
     * @throws Exception
     */
    private SItude getItude(SCell cell) throws Exception {
        SItude itude = new SItude();

        /** 采用Android默认的HttpClient */
        HttpClient client = new DefaultHttpClient();
        /** 采用POST方法 */
        HttpPost post = new HttpPost("http://www.google.com/loc/json");
        try {
            /** 构造POST的JSON数据 */
            JSONObject holder = new JSONObject();
            holder.put("version", "1.1.0");
            holder.put("host", "maps.google.com");
            holder.put("address_language", "zh_CN");
            holder.put("request_address", true);
            holder.put("radio_type", "gsm");
            holder.put("carrier", "HTC");

            JSONObject tower = new JSONObject();
            tower.put("mobile_country_code", cell.MCC);
            tower.put("mobile_network_code", cell.MNC);
            tower.put("cell_id", cell.CID);
            tower.put("location_area_code", cell.LAC);

            JSONArray towerarray = new JSONArray();
            towerarray.put(tower);
            holder.put("cell_towers", towerarray);

            StringEntity query = new StringEntity(holder.toString());
            post.setEntity(query);

            /** 发出POST数据并获取返回数据 */
            HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            BufferedReader buffReader = new BufferedReader(new InputStreamReader(entity.getContent()));
            StringBuffer strBuff = new StringBuffer();
            String result = null;
            while ((result = buffReader.readLine()) != null) {
                strBuff.append(result);
            }

            /** 解析返回的JSON数据获得经纬度 */
            JSONObject json = new JSONObject(strBuff.toString());
            JSONObject subjosn = new JSONObject(json.getString("location"));

            itude.latitude = subjosn.getString("latitude");
            itude.longitude = subjosn.getString("longitude");
            
            Log.i("Itude", ":"+itude.latitude + ":"+itude.longitude);
            
            Intent intent = new Intent();
            intent.setAction(SMS_GETLOCATION_BROADCAST);
            intent.putExtra("GetLocation", true);
            intent.putExtra("Longitude", itude.longitude);
            intent.putExtra("Latitude", itude.latitude);
            sendBroadcast(intent);
            timer.cancel();
            LocationService.this.stopSelf();
            
        } catch (Exception e) {
            Log.e(e.getMessage(), e.toString());
            throw new Exception("获取经纬度出现错误:"+e.getMessage());
        } finally{
            post.abort();
            client = null;
        }
        
        return itude;
    }
    
    @Override
    public void onDestroy() {
        Log.e(TAG, "======>>>onDestroy");
        location_manager.removeUpdates(locationListener);
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.e(TAG, "===>>>onBind");
        return null;
    }

    @Override
    public void onRebind(Intent intent) {
        Log.e(TAG, "===>>>onRebind");
        super.onRebind(intent);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.e(TAG, "===>>>onUnbind");
        return super.onUnbind(intent);
    }

}
